package org.dromara.business.jobhandler;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.business.domain.Advertising;
import org.dromara.business.domain.BusinessInformation;
import org.dromara.business.domain.User;
import org.dromara.business.domain.vo.BusinessConfigVo;
import org.dromara.business.domain.vo.UserVo;
import org.dromara.business.mapper.AdvertisingMapper;
import org.dromara.business.mapper.BusinessInformationMapper;
import org.dromara.business.mapper.UserMapper;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.common.mybatis.helper.DataPermissionHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.service.ISysUserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时修改
 */
@Slf4j
@Component
public class UserJobHandler {

    @Resource
    private UserMapper userMapper;

    @Resource

    private BusinessConfigService businessConfigService;

    @Resource
    private ISysUserService userService;

    @Resource
    private BusinessInformationMapper businessInformationMapper;
    @Resource
    private AdvertisingMapper advertisingMapper;


    /**
     * 定时修改用户的vip
     */


    /**
     * 定时刷新用户的刷新次数
     */

    @Scheduled(cron = "0 2 0 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void userScheduledTasks() {
        try {
            // 将过期vip修改
            updateAllUserVipExpiryTimes();
        } catch (Exception e) {
            log.warn("将过期vip修改: ", e);
        }

        try {
            // 将每个的分享次数归零
            uppbateUserByexchange();  // 注意：这里可能是个拼写错误，应该是 updateUserByExchange()
        } catch (Exception e) {
            log.warn("将每个的分享次数归零: ", e);
        }

        try {
            // 修改刷新状态
            UserRefreshScheduler();
        } catch (Exception e) {
            log.warn("修改刷新状态: ", e);
        }

        try {
            // 删除所有过期的信息
            deleteAllExpiredInformations();
        } catch (Exception e) {
            log.warn("删除所有过期的信息: ", e);
        }

        try {
            // 删除所有过期的广告
            deleteAllAdvertisements();
        } catch (Exception e) {
            log.warn("删除所有过期的广告: ", e);
        }

        try {
            // 修改普通用户发布次数
            updateUserHyNumber();
        } catch (Exception e) {
            log.error("修改普通用户发布次数: ", e);
        }

        try {
            // 修改代理状态
            handleExpiredProxyRenewal();
        } catch (Exception e) {
            log.error("修改代理状态: ", e);
        }
    }

    private void uppbateUserByexchange() {
        DataPermissionHelper.ignore( ()->userService.lambdaUpdate().set(SysUser::getExchange,0).update());

      log.warn(" 将每个的分享次数归零");
    }

    /**
     * 修改vip状态
     */
    public void updateAllUserVipExpiryTimes() {

        log.warn("=========================开始刷新用户的刷新次数=========================");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 构建更新条件
        UpdateWrapper<User> update = Wrappers.update();
        update.lt("gq_time", now); // gq_time 小于 当前时间
        update.ne("vip", 0);
        List<UserVo> userVos = userMapper.selectVoList(update);
        // 删除过期会员的所有信息
        if (ObjectUtil.isNotEmpty(userVos)) {
            deleteBusinessInformationByCreatedBy(userVos);
        }


        // 执行更新操作
        userMapper.update(null, update.set("vip", 0));


    }

    private void deleteBusinessInformationByCreatedBy(List<UserVo> userVos) {
        // 检查列表是否不为空
        if (ObjectUtil.isNotEmpty(userVos)) {
            // 提取用户ID
            List<Long> userIds = userVos.stream().map(UserVo::getUserId).toList();

            // 检查是否有用户ID需要处理
            if (!userIds.isEmpty()) {
                // 创建查询包装器
                QueryWrapper<BusinessInformation> queryWrapper = Wrappers.query();
                // 设置删除条件：create_by在用户ID列表中
                queryWrapper.in("create_by", userIds);
                queryWrapper.in("vip", 0);
                // 执行删除操作
                int deleteCount = businessInformationMapper.delete(queryWrapper);
                // 记录删除的信息数量
                log.warn("已删除 {}条由指定用户创建的信息。", deleteCount);
            }
        }
    }

    /**
     * 更新所有认得置顶状态
     */
    public void UserRefreshScheduler() {
        log.warn("=========================开始更新所有人的置顶状态=========================");
        Map<String, BigDecimal> directReferralCommissionMap = getDirectReferralCommissionMap();
        // 使用增强的 for 循环遍历 Map
        for (Map.Entry<String, BigDecimal> entry : directReferralCommissionMap.entrySet()) {
            String key = entry.getKey();
            BigDecimal value = entry.getValue();

            UpdateWrapper<User> update = Wrappers.update();
            update.set("refresh_times", value);
            update.eq("vip", key);
            int update1 = userMapper.update(null, update);
            log.warn("vip 是{}开始刷新用户的刷新次数", key, update1);
        }
    }

    /**
     * 删除所有过期的信息
     */
    private void deleteAllExpiredInformations() {
        // 创建一个QueryWrapper实例
        QueryWrapper<BusinessInformation> queryWrapper = Wrappers.query();
        // 设置删除条件：expiration_date小于当前时间
        queryWrapper.lt("expiration_date", LocalDateTime.now());
        // 执行删除操作
        int deleteCount = businessInformationMapper.delete(queryWrapper);
        log.warn("过期的信息有：{}条", deleteCount);
    }

    /**
     * 删除所有过期的广告
     */
    private void deleteAllAdvertisements() {

        // 创建一个QueryWrapper实例
        QueryWrapper<Advertising> queryWrapper = Wrappers.query();
        // 设置删除条件：expiration_date小于当前时间
        queryWrapper.lt("expiration_date", LocalDateTime.now());
        // 执行删除操作
        int deleteCount = advertisingMapper.delete(queryWrapper);
        log.warn("过期的广告有：{}条", deleteCount);


    }


    //定时处理过期代理
    private void handleExpiredProxyRenewal() {
        log.warn("=========================开始定时清理过期代理=========================");
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();
        // 构建更新条件
        UpdateWrapper<User> update = Wrappers.update();
        update.lt("approval_time", now);
        update.set("proxy_region", null);
        update.set("proxy_approval_status", "0");
        userMapper.update(null, update.set("is_proxy", '0'));
    }

    /**
     * 修改普通用户发布次数
     */
    private void updateUserHyNumber() {
        log.warn("=========================开始刷新普通用户发布次数刷=========================");
        List<BusinessConfigVo> vipList = businessConfigService.queryByKey("vip");
        BusinessConfigVo businessConfigVo = vipList.stream().filter(o -> 0 == o.getSortNo())
            .findFirst()
            .orElse(null);

        Integer hyNumber = 3;
        if (ObjectUtil.isNotEmpty(businessConfigVo)) {
            String[] split = businessConfigVo.getRemark().split("-");
            if (split.length > 0 && isNumeric(split[0])) {
                hyNumber = Integer.parseInt(split[0]);
            }
        }

        //修改普通用户的发布次数位
        updateUserPostCount(hyNumber);
    }

    /**
     * 修改普通用户的发布次数位
     *
     * @param hyNumber 发布次数
     */
    private void updateUserPostCount(Integer hyNumber) {
        QueryWrapper<BusinessInformation> queryWrapper = Wrappers.query();
        // 执行查询操作，获取所有广告信息列表
        List<BusinessInformation> advertisements = businessInformationMapper.selectList(queryWrapper);
        // 提取所有不重复的用户ID
        Set<Long> collect = advertisements.stream()
            .map(BusinessInformation::getUserId)
            .collect(Collectors.toSet());
        //查询所有的发布广人的id
        // 将Set转换为List，因为MyBatis-Plus的in方法通常接受List作为参数
        List<Long> userIdList = new ArrayList<>(collect);
        // 执行更新操作
        UpdateWrapper<User> update = Wrappers.update();
        if (ObjectUtil.isNotNull(userIdList) && !userIdList.isEmpty()) {
            update.notIn("user_id", userIdList);
        }
        update.eq("vip", "0");
        int hyNumber1 = userMapper.update(null, update.set("hy_number", hyNumber));
    }

    /**
     * @return
     */
    public Map<String, BigDecimal> getDirectReferralCommissionMap() {
        List<BusinessConfigVo> vipList = businessConfigService.queryByKey("vip");
        Map<String, BigDecimal> map = new HashMap<>();

        for (BusinessConfigVo businessConfigVo : vipList) {
            if (businessConfigVo.getRemark() != null && !businessConfigVo.getRemark().isEmpty()) {
                String[] split = businessConfigVo.getRemark().split("-");
                String numericString = split[1];
                if (split.length > 1 && isNumeric(numericString)) {
                    String sortNo = businessConfigVo.getSortNo() + "";
                    BigDecimal commissionRate = new BigDecimal(numericString);
                    map.put(sortNo, commissionRate);
                }
            }
        }

        return map;
    }


    // 辅助方法，用于检查字符串是否为数字（包括整数和小数）
    private boolean isNumeric(String str) {
        try {
            // 使用 BigDecimal 的构造函数，它可以处理整数和小数
            new BigDecimal(str);
            return true;
        } catch (NumberFormatException e) {
            // 捕获异常，表示字符串不是有效的数字格式
            return false;
        }
    }

}
